# 创建序列化器
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer

from mall import settings
from .models import User
import re
from django_redis import get_redis_connection


# username,password,password2,mobile,sms_code,allow
class RegisterCreateSerializer(ModelSerializer):
    password2 = serializers.CharField(label='确认密码',write_only=True,allow_null=False,allow_blank=False)
    sms_code = serializers.CharField(label='短信验证码',min_length=6,max_length=6,write_only=True)
    allow = serializers.CharField(label='同意协议',write_only=True,
                                  allow_null=False, allow_blank=False)
    # 需要有token字段
    token = serializers.CharField(label='增加的token',read_only=True)

    class Meta:
        model = User
        fields = ['id','username','password','mobile','password2','sms_code','allow','token']
        extra_kwargs = {
            'id':{'read_only':True},
            'username':{
                'min_length':5,
                'max_length':20,
                'error_messages':{
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length':'仅允许5-20个字符的用户名'
                } },
            'password':{
                'write_only':True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码'
                }
            }

        }

    # 校验数据
    # 校验手机格式
    def validated_mobile(self,mobile):
        if not re.match(r'^1[345789]\d{9}$',mobile):
            raise serializers.ValidationError('手机号格式错误')
        return mobile

    # 校验allow参数
    def validate_allow(self, allow):
        if allow != 'true':
            raise serializers.ValidationError('您未同意协议')
        return allow

    # 校验密码是否相等和短信验证码
    def validate(self, attrs):
        # 验证密码是否相等
        password = attrs.get('password')
        password2 = attrs.get('password2')
        if password != password2:
            raise serializers.ValidationError('两次密码不一样')

        code = attrs['sms_code']
        # print(code)
        mobile = attrs['mobile']
        # 连接redis取出短信验证码
        redis_coon =get_redis_connection('code')
        redis_text = redis_coon.get('sms_%s'%mobile)
        # print(redis_text)
        if redis_text is None:
            raise serializers.ValidationError('验证码过期')
        if redis_text.decode() != code:
            raise serializers.ValidationError('短信验证码错误')
        return attrs
    def create(self, validated_data):
        # 删除多余字段
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']
        # 创建用户
        user = super().create(validated_data)
        # 给密码加密
        user.set_password(validated_data['password'])
        user.save()
        # 需要在创建了user之后,我们采用jwt生成一个token返回

        from rest_framework_jwt.settings import api_settings
        # 补充生成记录登录状态的token
        # 获取的2个方法：
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        # 调用这2个方法，把用户信息给payload
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        # 把token信息给user,(返回user实例，里面增加了一个token信息。)
        user.token = token
        return user


# 定义用户中心的序列化器
class UserCenterInfoSeriakizer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('id','username','mobile','email','email_active')


# 邮件更新和校验的序列化器
class EmailUpdateSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('id','email')
        extra_kwargs = {
            'email': {
                'required':True
            }
        }

    def update(self, instance, validated_data):
        # 获取emali
        email = validated_data.get('email')
        instance.email = email
        instance.save()
        # 发送邮件
        from django.core.mail import send_mail
        # subject :邮件标题
        # message：普通邮件正文，普通字符串
        # from_email：发件人
        # recipient_list：收件人列表
        # html_message = None：多媒体邮件正文，可以是html字符串
        subject='美多商城激活邮件'
        message=''
        from_email= settings.EMAIL_FROM
        recipient_list=[email]
        # 生成一个由user_id和email组成的token拼接成的url
        verify_url = instance.generic_active_url()
        html_message = '<p>尊敬的用户您好！</p>' \
                       '<p>感谢您使用美多商城。</p>' \
                       '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                       '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)
        send_mail(subject,
                  message,
                  from_email,
                  recipient_list,
                  html_message=html_message)

        # send_mail(subject,
        #           message,
        #           from_email,
        #           recipient_list,html_message=html_message)

        # from celery_tasks.email.tasks import send_verify_email
        #
        # send_verify_email.delay(subject,
        #                         message,
        #                         from_email,
        #                         recipient_list,
        #                         html_message=html_message)

        return instance



